package com.fxc.Handler;

import com.fxc.util.ResultEntity;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fxc.entity.Employee;

import java.util.ArrayList;
import java.util.List;

@RestController
public class EmployeeHandler {

    private Logger logger = LoggerFactory.getLogger(EmployeeHandler.class);

    @HystrixCommand(fallbackMethod = "getEmpWithCircuitBreakerBackUp")
    @RequestMapping("/provider/get/emp/with/circuit/breaker")
    public ResultEntity<Employee> getEmpWithCircuitBreaker(@RequestParam("signal") String signal){

        if ("quick-bang".equals(signal)) {
            throw new RuntimeException();
        }

        if ("slow-bang".equals(signal)){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return ResultEntity.successWithData(new Employee(666, "success", 88.88));
    }

    public ResultEntity<Employee> getEmpWithCircuitBreakerBackUp(@RequestParam("signal") String signal){

        String message = "方法执行出现问题，执行断路 signal = " + signal;

        return ResultEntity.successWithData(new Employee(666, message, 88.88));
    }

    @RequestMapping("/provider/get/employee")
    public Employee getEmployeeRemote(){

        // 获取当前服务的端口号
        // int serverPort = request.getServerPort();

        return new Employee(555,"tom555 ",32.21);
    }


    @RequestMapping("/provider/get/employee/by/id")
    public Employee getEmployeeById(@RequestParam("empId") Integer empId){

        return new Employee(666, "tom66", 23.23);
    }

    @RequestMapping("/provider/save/emp")
    public Employee saveEmploy(@RequestBody Employee employee){

        return employee;
    }

    @RequestMapping("/provider/list/remote")
    public List<Employee> getListEmpListRemote(@RequestParam("keyword") String keyword){

        logger.info("keyword" + keyword);
        ArrayList<Employee> list = new ArrayList<>();

        list.add(new Employee(33,"ae3", 90.23));
        list.add(new Employee(44,"ae4", 920.23));
        list.add(new Employee(55,"ae5", 903.23));

        return list;
    }

//    @RequestMapping("/provider/get/employee")
//    public Employee getEmployeeRemote(HttpServletRequest request){
//
//        // 获取当前服务的端口号
//        int serverPort = request.getServerPort();
//
//        return new Employee(555,"tom555 " + serverPort,32.21);
//    }
}
